<?php

namespace app\common\model\coupon;

use think\Model;


class Log extends Model
{





    // 表名
    protected $name = 'coupon_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'state_text',
        'goods_type_text'
    ];



    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2'), '3' => __('Type 3')];
    }

    public function getStateList()
    {
        return ['0' => __('State 0'), '1' => __('State 1'), '2' => __('State 2')];
    }

    public function getGoodsTypeList()
    {
        return ['0' => __('Goods_type 0'), '1' => __('Goods_type 1')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getGoodsTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['goods_type']) ? $data['goods_type'] : '');
        $list = $this->getGoodsTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    //更新过期优惠券
    public static function editState($user_id)
    {
        return  self::where('user_id', $user_id)->where('enddate', '<', date('Y-m-d'))->where('state', 1)->update(['state' => 0]) ? true : false;
    }
    //使用优惠券
    public static function useCoupon($coupon_id, $pay_amount)
    {
        if ($coupon_id) {
            $coupon = Log::get($coupon_id);
            if (!$coupon) return false;
            if ($coupon->state!=1) {
                exception('该优惠券已使用');
            }
            if ($pay_amount < $coupon->money) {
                exception('该优惠券满' . $coupon->money . '元可使用', 20002);
            }
            $params['coupon_amount'] = $coupon->price;
            $params['pay_amount'] = $pay_amount - $params['coupon_amount'];
            $coupon->save(['state' => 2]);
            return $params;
        }
        return false;
    }
    public function coupon()
    {
        return $this->belongsTo('app\common\model\Coupon', 'coupon_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
